import { Button, Card, Form, Input, Select } from 'antd'
import { CheckOutlined, CloseOutlined } from '@ant-design/icons'
import { TaskItem } from '@/types'
import { taskItemPriorityConfig, taskItemTypeConfig } from '../config'
import { TASK_PRIORITY } from '@/enums'
import { useState, useEffect } from 'react'
import '../styles/taskCard.css'

const { Option } = Select
const { TextArea } = Input

export default function TaskNodeEdit({
  task,
  onSave,
  onCancel
}: {
  task?: TaskItem // 没有 task 就是新增
  onSave: (values: TaskItem) => void
  onCancel: () => void
}) {
  const [form] = Form.useForm()
  const [isSubmitting, setIsSubmitting] = useState(false)

  // 设置默认值
  useEffect(() => {
    if (!task) {
      // 新增任务时设置默认值
      form.setFieldsValue({
        priority: TASK_PRIORITY.LOW, // 默认优先级为低
        progress: 0,
        status: 'not started'
      })
    }
  }, [task, form])

  const handleSave = async () => {
    try {
      setIsSubmitting(true)
      const values = await form.validateFields()

      // 构建完整的任务对象
      const taskData: TaskItem = {
        ...values,
        id: task?.id || Date.now().toString(),
        progress: task?.progress || 0,
        status: task?.status || 'not started',
        createdAt: task?.createdAt || new Date(),
        updatedAt: new Date(),
        dueDate: values.dueDate ? new Date(values.dueDate) : undefined
      }

      onSave(taskData)
    } catch (error) {
      console.error('表单验证失败:', error)
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <Card size="small" className="card" type="inner">
      <Form form={form} layout="horizontal" initialValues={task} className="w-full">
        <div className="grid grid-cols-1 md:grid-cols-4 lg:grid-cols-5 gap-4">
          {/* 左侧：标题和描述 */}
          <div className="md:col-span-2 lg:col-span-3 space-y-4">
            {/* 标题 */}
            <Form.Item
              name="title"
              label="标题"
              labelCol={{ span: 24 }}
              wrapperCol={{ span: 24 }}
              rules={[{ required: true, message: '请输入任务标题' }]}
            >
              <Input placeholder="请输入任务标题" size="middle" />
            </Form.Item>

            {/* 描述 */}
            <Form.Item
              name="description"
              label="描述"
              labelCol={{ span: 24 }}
              wrapperCol={{ span: 24 }}
            >
              <TextArea placeholder="请输入任务描述" rows={3} />
            </Form.Item>
          </div>

          {/* 右侧：类型和优先级 */}
          <div className="md:col-span-1 lg:col-span-1">
            {/* 类型 */}
            <Form.Item
              name="type"
              label="任务类型"
              labelCol={{ span: 24 }}
              wrapperCol={{ span: 24 }}
              rules={[{ required: true, message: '请选择任务类型' }]}
            >
              <Select placeholder="选择类型" size="middle">
                {Object.entries(taskItemTypeConfig).map(([key, item]) => (
                  <Option key={key} value={key}>
                    <span style={{ color: item.color }}>{item.title}</span>
                  </Option>
                ))}
              </Select>
            </Form.Item>

            {/* 优先级 */}
            <Form.Item
              name="priority"
              label="优先级"
              labelCol={{ span: 24 }}
              wrapperCol={{ span: 24 }}
              required
            >
              <Select placeholder="选择优先级" size="middle">
                {Object.entries(taskItemPriorityConfig).map(([key, item]) => (
                  <Option key={key} value={parseInt(key)}>
                    <span style={{ color: item.color }}>{item.title}</span>
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </div>

          {/* 操作按钮 */}
          <div
            className="md:col-span-1 flex items-end justify-end gap-2"
            style={{ borderColor: 'var(--border)' }}
          >
            <Button icon={<CloseOutlined />} onClick={onCancel} size="middle">
              取消
            </Button>
            <Button
              type="primary"
              icon={<CheckOutlined />}
              onClick={handleSave}
              loading={isSubmitting}
              size="middle"
              style={{ color: '#fff' }}
            >
              {task ? '保存' : '创建'}
            </Button>
          </div>
        </div>
      </Form>
    </Card>
  )
}
